<template>
  <div>
    <h1>三级分类页面</h1>
    <el-input placeholder="输入关键字进行过滤" v-model="filterText"> </el-input>
    <el-switch
      v-model="draggable"
      active-color="#13ce66"
      inactive-color="#ff4949"
    >
    </el-switch>
    开启拖拽
    <el-tree
      @node-drop="nodeDrop"
      :draggable="draggable"
      :allow-drop="allowDrop"
      :data="data"
      :props="defaultProps"
      :expand-on-click-node="false"
      :filter-node-method="filterNode"
      ref="tree"
    >
      <span slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button
            v-if="data.catLevel != 3"
            type="text"
            size="mini"
            @click="() => append(data)"
          >
            Append
          </el-button>
          <el-button type="text" size="mini" @click="() => update(data)">
            Update
          </el-button>
          <el-button
            v-if="node.childNodes.length == 0"
            type="text"
            size="mini"
            @click="() => remove(data)"
          >
            Delete
          </el-button>
        </span>
      </span>
    </el-tree>
    <!-- 编辑分类弹窗 -->
    <el-dialog title="分类编辑" :visible.sync="dialogFormVisible">
      <h1>{{ category }}</h1>
      <el-form :model="category">
        <el-form-item label="分类名称" label-width="210px">
          <el-input v-model="category.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label-width="310px">
          <el-button type="primary" @click="save">保存</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
export default {
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    },
  },
  data() {
    return {
      draggable: false,
      pid: 0,
      level: 1,
      countLevel: 1,
      filterText: "",
      category: {
        sort: 0,
        showStatus: 1,
      },
      dialogFormVisible: false,
      data: [],
      defaultProps: {
        children: "children",
        label: "name",
      },
      updateNodes: []
    };
  },
  methods: {
    //拖拽成功
    nodeDrop(draggingNode, dropNode, type) {
      //数据收集
      if (type == "before" || type == "after") {
        //给pid赋值
        this.pid = dropNode.data.parentCid;
        //层级赋值
        this.level = dropNode.level;
      } else if (type == "inner") {
        this.pid = dropNode.data.catId;
        this.level = dropNode.level + 1;
      }
      this.collectorList(
        dropNode.parent.childNodes,
        draggingNode.level != dropNode.level,
        draggingNode.childNodes
      );
      console.log("收集之后的结果", this.updateNodes);
      //修改结点,同步数据库
      this.$http({
        url: this.$http.adornUrl('/product/category/updateNodes'),
        method: "post",
        data: this.$http.adornData(this.updateNodes, false)
      }).then(({ data }) => {
        console.log(data);
        this.$message({
          message: "编辑成功",
          type: "success",
        });
      });
      this.getDataList();
    },
    //收集元素
    collectorList(nodes, levelFlag = false, childNodes) {
      console.log("需要收集的对象", nodes);
      this.updateNodes = [];
      for (var i = 0; i < nodes.length; i++) {
        var obj = {
          catId: nodes[i].data.catId,
          name: nodes[i].data.name,
          catLevel: this.level,
          parentCid: this.pid,
          sort: i,
        };
        this.updateNodes.push(obj);
      }
      //收集子元素
      if (levelFlag) {
        for (var i = 0; i < childNodes.length; i++) {
          var obj = {
            catId: childNodes[i].data.catId,
            name: childNodes[i].data.name,
            catLevel: this.level + 1,
            sort: i,
          };
          this.updateNodes.push(obj);
        }
      }
    },
    //判断是否可以拖拽
    /**
     * 返回值
     * true 可以放置
     * false 不可以放置
     * */
    allowDrop(draggingNode, dropNode, type) {
      this.getCountLevel(draggingNode);
      if (type == "prev" || type == "next") {
        //放置目标节点前或后
        //层数为1 必可放置
        if (this.countLevel == 1) return true;
        //层数为2 可放置结点层级为1，2
        if (this.countLevel == 2 && dropNode.level != 3) return true;
        //层数为3 可放置结点层级为1
        if (this.countLevel == 3 && dropNode.level == 1) return true;
      } else if (type == "inner") {
        //放置目标节点内部
        //层数为1 可放置结点层级为1，2
        if (this.countLevel == 1 && dropNode.level != 3) return true;
        //层数为2 可放置结点层级为1
        if (this.countLevel == 2 && dropNode.level == 1) return true;
        //层数为3 不可放置内部
      }
      return false;
    },
    //获取当前结点有多少层级
    getCountLevel(node) {
      this.countLevel = 1;
      if (node.childNodes.length > 0) {
        this.countLevel = 2;
        for (let i in node.childNodes) {
          if (node.childNodes[i].childNodes.length > 0) {
            this.countLevel = 3;
            return;
          }
        }
      }
    },
    //过滤结点
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    //提交数据
    save() {
      console.log(this.category);
      let adornUrl =
        this.category.catId != undefined
          ? "/product/category/update"
          : "/product/category/save";
      this.$http({
        url: this.$http.adornUrl(adornUrl),
        method: "post",
        data: this.$http.adornData(this.category, false),
      }).then(({ data }) => {
        console.log(data);
        this.$message({
          message: "编辑成功",
          type: "success",
        });
      });
      this.getDataList();
      this.dialogFormVisible = false;
    },
    //分类添加弹窗方法
    append(node) {
      this.category = {
        sort: 0,
        showStatus: 1,
      };
      console.log("弹窗添加的对象：", node);
      this.category.parentCid = node.catId;
      this.category.catLevel = node.catLevel + 1;
      this.dialogFormVisible = true;
    },
    //分类修改弹窗方法
    update(node) {
      console.log("弹窗修改的对象：", node);
      this.dialogFormVisible = true;
      //回显
      this.$http({
        url: this.$http.adornUrl(`/product/category/info/${node.catId}`),
        method: "get",
      }).then(({ data }) => {
        console.log("回显的对象为：", data);
        this.category.catId = data.category.catId;
        this.$set(this.category, "name", data.category.name);
        this.category.catLevel = data.category.catLevel;
        this.category.parentCid = data.category.parentCid;
        this.category.sort = data.category.sort;
        this.category.showStatus = data.category.showStatus;
      });
    },
    //分类删除方法
    remove(node) {
      console.log("弹窗删除的对象", node);
      let ids = [node.catId];
      this.$http({
        url: this.$http.adornUrl("/product/category/delete"),
        method: "delete",
        data: this.$http.adornData(ids, false),
      }).then(({ data }) => {
        console.log("删除", data);
        this.getDataList();
        this.$message({
          message: "删除成功",
          type: "success",
        });
      });
    },
    //声明一个方法去查询商品服务得到三级分类结果
    //axios
    getDataList() {
      //请求商品服务查询三级列表
      this.$http({
        url: this.$http.adornUrl("/product/category/tree/list"),
        method: "get",
        params: this.$http.adornParams(),
      }).then(({ data }) => {
        console.log(data);
        this.data = data.data;
        console.log(this.data);
      });
    },
  },
  created() {
    this.getDataList();
  }
};
</script>
